package com.wswy.wzcx.ui.dmv;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import com.wswy.wzcx.R;
import java.util.ArrayList;
import java.util.List;

abstract class PopupListAdapter<T> extends RecyclerView.Adapter<PopupListAdapter.ItemViewHolder> implements
    OnClickListener{


  private List<T> datas= new ArrayList<>();

  private int selectedPosition=-1;

  void setNewData(List<T> data){
    datas.clear();
    if(data != null){
      datas.addAll(data);
    }
    selectedPosition = -1;
    notifyDataSetChanged();
  }


  @NonNull
  @Override
  public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new ItemViewHolder((LayoutInflater.from(parent.getContext())
        .inflate(R.layout.layout_item_text, parent, false)));
  }

  @Override
  public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
    holder.itemView.setOnClickListener(this);
    T data = datas.get(position);

    holder.itemView.setTag(R.id.item_position,position);
    holder.itemView.setTag(R.id.item_data, data);

    if(enableChangeColor()){

      if(selectedPosition == position){
        holder.itemView.setBackgroundColor(Color.WHITE);
      }else {
        holder.itemView.setBackgroundColor(Color.TRANSPARENT);
      }

    }

    bindData(holder.textView,data);
  }

  @Override
  public int getItemCount() {
    return datas.size();
  }

  @Override
  public void onClick(View v) {
    final int oldPos = selectedPosition;

    int newPos = (int) v.getTag(R.id.item_position);
    T data = (T) v.getTag(R.id.item_data);

    if(oldPos != newPos){

      if(enableChangeColor()){
        selectedPosition = newPos;
        if(oldPos != -1){
          notifyItemChanged(oldPos);
        }
        notifyItemChanged(newPos);
      }

      onItemClick(data,newPos);

    }




  }



  protected boolean enableChangeColor(){
    return true;
  }

  protected abstract void bindData(TextView textView,T t);
  protected abstract void onItemClick(T data,int position);

  static class ItemViewHolder extends ViewHolder{

    TextView textView;

    ItemViewHolder(View itemView) {
      super(itemView);
      textView = itemView.findViewById(R.id.tv_text);
    }
  }
}
